package com.zuxia.impDao;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.map.HashedMap;
import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.zuxia.iDao.StaffindoDAOI;
import com.zuxia.po.Departmentinfo;
import com.zuxia.po.Positioninfo;
import com.zuxia.po.Powerinfo;
import com.zuxia.po.Staffindo;

/**
 * 员工表dao实现类
 * @author 谌华勇
 *
 * 2018年11月14日下午3:13:59
 */
public class StaffindoDAO extends HibernateDaoSupport implements StaffindoDAOI {
	private static final Logger log = LoggerFactory
			.getLogger(StaffindoDAO.class);
	// property constants
	public static final String SINAME = "siname";
	public static final String SISEX = "sisex";
	public static final String SIPWD = "sipwd";
	public static final String SIPHONE = "siphone";
	public static final String SIID_CARD = "siidCard";
	public static final String SIADDRESS = "siaddress";

	protected void initDao() {
		// do nothing
	}

	public int save(Staffindo transientInstance){
		log.debug("saving Staffindo instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			return 0;
		}
		return 1;
	}
	

	public int delete(Staffindo persistentInstance) {
		log.debug("deleting Staffindo instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			return 0;
		}
		return 1;
	}
	
	public int selAllCout(String serachstuName){
		log.debug("sel ALL Staffindo For PageCount");
		StringBuffer hql = new StringBuffer("select count(*) from Staffindo as a ");
		if(!serachstuName.equals("")) {
			hql.append("where siname like "+"'%"+serachstuName+"%'");
		}
		long id=(Long) getHibernateTemplate().iterate(hql.toString()).next();
		return (int)id;
	}

	public List<Staffindo> selAllStaInfoByPageModel(final String pageNumber, final String limit, String serachstuName) {
		//final Object[] values
		log.debug("selAllStaInfoByPageModel"); 
		final StringBuffer hql = new StringBuffer("from Staffindo as a ");
		if(!serachstuName.equals("")) {
			hql.append("where siname like "+"'%"+serachstuName+"%'");
		}
		List list = getHibernateTemplate().executeFind(new HibernateCallback() {
			   
			   public Object doInHibernate(Session session) throws HibernateException,
			     SQLException {
			    Query query = session.createQuery(hql.toString());
			    //这个用于扩展多条件查询用到的
			   /* for (int i = 0; i < values.length; i++) {
			     query.setParameter(i, values[i]);
			    }*/
			    int p = Integer.parseInt(pageNumber);
			    int l = Integer.parseInt(limit);
			    int a = (p-1)*l;
			    List result = query.setFirstResult(a)
			        .setMaxResults(l)
			        .list();
			    /*List result = query
				        .list();*/
			    System.out.println("员工dao中查询到了数据"+result);
			    return result;
			   }
			  });
		
			  return list;
	}

	/**
	 * 查询员工，返回map用于存为session
	 * @param phone
	 * @param pwd
	 * @return
	 */
	public Map<String, Object> selUserByPhoneAndPwd(String phone, String pwd) {
		Map<String, Object> mapForSession = new HashedMap();
		String queryString = "select a.siid,a.siname,a.powerinfo.piname from Staffindo as a  where a.siphone=? and a.sipwd=?";
		List listAdmin = getHibernateTemplate().find(queryString, phone,pwd);
		Iterator iter = listAdmin.iterator();
		while (iter.hasNext()) {
			//由于上面是只查询管理员编号和姓名，所以数据被hib封装在了一个object数组中了
			Object[] obj = (Object[])iter.next();
			System.out.println("员工登录成功：编号："+obj[0]+"姓名："+obj[1]+"权限："+obj[2]);
			//封装进Map
			mapForSession.put("id", obj[0]);
			mapForSession.put("name", obj[1]);
			mapForSession.put("piname", obj[2]);
		}
		return mapForSession;
	}

	public Staffindo findById(java.lang.Integer id) {
		log.debug("getting Staffindo instance with id: " + id);
		try {
			Staffindo instance = (Staffindo) getHibernateTemplate().get(
					"com.zuxia.po.Staffindo", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Staffindo instance) {
		log.debug("finding Staffindo instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findByProperty(java.lang.String, java.lang.Object)
	 */
	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Staffindo instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Staffindo as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findBySiname(java.lang.Object)
	 */
	public List findBySiname(Object siname) {
		return findByProperty(SINAME, siname);
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findBySisex(java.lang.Object)
	 */
	public List findBySisex(Object sisex) {
		return findByProperty(SISEX, sisex);
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findBySipwd(java.lang.Object)
	 */
	public List findBySipwd(Object sipwd) {
		return findByProperty(SIPWD, sipwd);
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findBySiphone(java.lang.Object)
	 */
	public List findBySiphone(Object siphone) {
		return findByProperty(SIPHONE, siphone);
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findBySiidCard(java.lang.Object)
	 */
	public List findBySiidCard(Object siidCard) {
		return findByProperty(SIID_CARD, siidCard);
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findBySiaddress(java.lang.Object)
	 */
	public List findBySiaddress(Object siaddress) {
		return findByProperty(SIADDRESS, siaddress);
	}

	/* (non-Javadoc)
	 * @see com.zuxia.impDao.StaffindoDAOI#findAll()
	 */
	public List findAll() {
		log.debug("finding all Staffindo instances");
		try {
			String queryString = "from Staffindo";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public int merge(Staffindo detachedInstance) {
		log.debug("merging Staffindo instance");
		try {
			Staffindo result = (Staffindo) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result==null?0:1;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			return 0;
		}
	}

	public int attachDirty(Staffindo instance) {
		log.debug("attaching dirty Staffindo instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			return 0;
		}
		return 1;
	}

	public void attachClean(Staffindo instance) {
		log.debug("attaching clean Staffindo instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static StaffindoDAOI getFromApplicationContext(ApplicationContext ctx) {
		return (StaffindoDAOI) ctx.getBean("StaffindoDAO");
	}

	public Boolean userShowPwd(String name, String pwd) {
		String queryString ="from Staffindo as s where  s.siname=? and s.sipwd=?  ";
		List list = getHibernateTemplate().find(queryString, name,pwd);
		if(list.size()>0){
			return true;
		}
		return false;
	}

	public Boolean userUpdatePwd(String name, String pwd, String xpwd) {
		Boolean b=false;
		Transaction trans=getSession().beginTransaction();
		String HQL="update Staffindo  set sipwd=?  where sipwd=? and siname=?";
		Query queryupdate=getSession().createQuery(HQL);
		queryupdate.setString(0, xpwd);
		queryupdate.setString(1, pwd);
		queryupdate.setString(2, name);
		int ret=queryupdate.executeUpdate();
		if(ret>0){
			b=true;
		}
		trans.commit();
		return b;
	}
}